package com.hehe.auth.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.stereotype.Component;

import com.hehe.auth.token.provider.DeviceTokenGranter;
import com.hehe.auth.token.provider.SMSTokenGranter;
import com.hehe.auth.token.provider.WechatTokenGranter;
@Component
public class TokenGranterDelegater implements TokenGranter{
	private CompositeTokenGranter delegate;
	@Autowired
	private AuthorizationServerTokenServices tokenServices;
	@Autowired
	private ClientDetailsService clientDetailsService;
	@Autowired
	private OAuth2RequestFactory  oAuth2RequestFactory ;
	@Autowired
	private AuthenticationManager authenticationManager;
	
	public TokenGranterDelegater() {
		List<TokenGranter> granter = new ArrayList<>();
		granter.add(new DeviceTokenGranter(tokenServices,clientDetailsService,oAuth2RequestFactory));
		granter.add(new SMSTokenGranter(tokenServices, clientDetailsService, oAuth2RequestFactory));
		granter.add(new WechatTokenGranter(tokenServices, clientDetailsService, oAuth2RequestFactory));
		granter.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, clientDetailsService, oAuth2RequestFactory));
		
		delegate = new CompositeTokenGranter(granter);
	}
	@Override
	public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {
	        return delegate.grant(grantType, tokenRequest);
	}
	
}
